package book

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func search(c *gin.Context) {
	name := c.DefaultQuery("name", "")
	c.JSON(http.StatusOK, gin.H{
		"msg":  "ok",
		"name": name,
	})
}

func list(c *gin.Context) {
	var msg struct {
		Msg  string `json:"msg"`
		Code int    `json:"code"`
	}
	msg.Msg = "suc"
	msg.Code = 0
	c.JSON(http.StatusOK, msg)
}

func create(c *gin.Context) {
	currentUser, ok := c.Get("currentUser")
	if ok {
		fmt.Println(currentUser)
	}
	c.JSON(http.StatusCreated, gin.H{
		"msg":  "ok",
		"user": currentUser,
	})
}

func upload(c *gin.Context) {
	file, err := c.FormFile("image")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": err.Error(),
		})
	}
	log.Println(file.Filename)
	dst := fmt.Sprintf("./%s", file.Filename)
	c.SaveUploadedFile(file, dst)
	c.JSON(http.StatusOK, gin.H{
		"msg": fmt.Sprintf("%s uploaded!", file.Filename),
	})
}

func uploadMulti(c *gin.Context) {
	form, _ := c.MultipartForm()
	files := form.File["file"]
	for index, file := range files {
		dst := fmt.Sprintf("./%s_%d", file.Filename, index)
		c.SaveUploadedFile(file, dst)
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": fmt.Sprintf("%d uploaded!", len(files)),
	})

}
